package com.demo.common.util;

import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import io.micrometer.tracing.Span;
import io.micrometer.tracing.TraceContext;
import io.micrometer.tracing.Tracer;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;

/**
 * TracerUtil
 * 
 * @author demo
 * @data 2023-01-12 21:53:46
 */
@Slf4j
@Component
public class TracerUtil {
    private static Tracer tracer;

    @Autowired
    public void setTracer(Tracer tracer) {
        TracerUtil.tracer = tracer;
    }

    @PostConstruct
    public void init() {
        log.info("{} inited", TracerUtil.class.getSimpleName());
    }

    /**
     * 获取currentSpan
     */
    public static Span getCurrentSpan() {
        return tracer.currentSpan();
    }

    /**
     * 获取traceId
     */
    public static String getTraceId() {
        Span span = getCurrentSpan();
        if (span == null) {
            return null;
        }
        return span.context().traceId();
    }

    /**
     * 获取spanId
     */
    public static String getSpanId() {
        Span span = getCurrentSpan();
        if (span == null) {
            return null;
        }
        return span.context().spanId();
    }

    /**
     * 获取traceHeaders
     */
    public static Map<String, String> getTraceHeaders() {
        Span span = getCurrentSpan();
        if (span == null) {
            return null;
        }
        try {
            TraceContext traceContext = span.context();
            Map<String, String> headers = new HashMap<>();
            headers.put("TraceId", traceContext.traceId());
            headers.put("SpanId", traceContext.spanId());
            String parentIdString = traceContext.parentId();
            if (parentIdString != null) {
                headers.put("ParentSpanId", parentIdString);
            }
            return headers;
        } catch (Exception e) {
            log.error("获取TraceHeaders异常", e);
            return null;
        }
    }

}
